import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Form, DatePicker, Button, Tooltip } from 'antd';
import styles from './index.less';
import dataTime from '../../../utils/dataTime';

const FormItem = Form.Item;
const dateFormat = 'YYYY/MM/DD';
const { RangePicker } = DatePicker;
const SolveeProportion = React.lazy(() => import('./SolveeProportion'));
const IntroduceRow = React.lazy(() => import('./IntroduceRow'));
const ProportionSales = React.lazy(() => import('./ProportionSales')); // 饼图

@connect(({ answerRatioStatis, loading }) => ({
  answerRatioStatis,
  loading: loading.effects['answerRatioStatis/fetch'],
}))
class AnswerRatio extends Component {
  state = {
    list: [],
    total: '',
    salesType: 'all',
    solveType: 'alls',
    allTitle: '总体问答比例',
    allTitleA: '已解决/未解决比例',
    colors: ['#3bbbbb', '#785ea7', '#f1cd3d'],
    colorsa: ['#00c2f3', '#f7b136'],
    curve: '1',
  };

  // eslint-disable-next-line react/sort-comp
  componentDidMount() {
    const { dispatch, currentUser } = this.props;
    const { beginTime, overTime } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'answerRatioStatis/fetch',
        payload: { robotId: currentUser.robotId, from: beginTime, to: overTime },
        callback: res => {
          console.log(res);
        },
      });
    });
  }

  componentWillMount() {
    let sysTime = dataTime.formatDate(new Date().getTime()); // 初始时间
    let toTime = moment()
      .subtract('days', 7)
      .format('YYYY/MM/DD'); // 初始时间
    this.setState({
      beginTime: toTime.replace(/\//g, '-'),
      overTime: sysTime.replace(/\//g, '-'),
    });
    console.log(sysTime);
  }

  // 查看
  handleSubmit = () => {
    if (this.state.beginTime === this.state.overTime) {
      this.setState({ curve: '0' });
    } else {
      this.setState({ curve: '1' });
    }
    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    let usercz = this.props.form.resetFields(); // 重置表单数据
    console.log(userInfo);
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'answerRatioStatis/fetch',
        payload: {
          robotId: currentUser.robotId,
          from: this.state.beginTime,
          to: this.state.overTime,
        },
        callback: res => {
          console.log(res);
        },
      });
    });
  };

  // 饼图A回调
  handleChangeSalesType = e => {
    console.log(e.target.value);
    if (e.target.value === 'all') {
      this.setState({
        allTitle: '总体问答比例',
        colors: ['#3bbbbb', '#785ea7', '#f1cd3d', '#ccc'],
      });
    }
    if (e.target.value === 'online') {
      this.setState({
        allTitle: '问答渠道比例',
        colors: ['#0ba29a', '#ea5853', '#f8b62b', '#ccc'],
      });
    }
    this.setState({
      salesType: e.target.value,
    });
  };

  handleChangesolveType = e => {
    if (e.target.value === 'alls') {
      this.setState({
        allTitleA: '已解决/未解决比例',
        colorsa: ['#00c2f3', '#f7b136', '#ccc'],
      });
    }
    if (e.target.value === 'onlines') {
      this.setState({
        allTitleA: '用户库已解决/未解决比例',
        colorsa: ['#74ae16', '#e23e0d', '#ccc'],
      });
    }
    console.log(e.target.value);
    this.setState({
      solveType: e.target.value,
    });
  };

  // 日期选择｛开始日期——结束日期｝
  onChange = (date, dateString) => {
    this.setState({
      beginTime: dateString[0].replace(/\//g, '-'),
      overTime: dateString[1].replace(/\//g, '-'),
    });

    // console.log(beginTime, overTime);
  };

  render() {
    const { salesType, solveType } = this.state;
    const { getFieldDecorator } = this.props.form;
    const { answerRatioStatis, loading } = this.props;
    const {
      chatCountList, //聊天数列表
      systemCountList, //系统计数表
      unknownCountList, //未知计数表
      userCountList, //用户数量列表
      hitAllData, // 问答比例 -- 总体问答比例
      channelData, // 问答比例 -- 问答渠道比例
      resolvedData, // 解决比例 -- 已解决/未解决比例
      resolvedInUserData, // 解决比例 -- 用户库已解决/未解决比
    } = answerRatioStatis;
    console.log(chatCountList);
    let salesPieData;
    let solvePieDataA;
    if (salesType === 'all') {
      let arr = [];
      hitAllData.map((item, index) => {
        if (hitAllData[index].y === 0) {
          let a = 1;
          arr.push(a);
        }
      });
      if (hitAllData.length === arr.length) {
        let fell = { x: '暂无数据', y: 1 };
        hitAllData.push(fell);
        this.setState({ colors: ['#3bbbbb', '#785ea7', '#f1cd3d', '#ccc'] });
      }
      salesPieData = hitAllData;
    } else {
      let arr = [];
      channelData.map((item, index) => {
        if (channelData[index].y === 0) {
          let a = 1;
          arr.push(a);
        }
      });
      if (channelData.length === arr.length) {
        let fell = { x: '暂无数据', y: 1 };
        this.setState({ colors: ['#0ba29a', '#ea5853', '#f8b62b', '#ccc'] });
        channelData.push(fell);
      }
      salesPieData = channelData;
    }

    if (solveType === 'alls') {
      let arr = [];
      resolvedData.map((item, index) => {
        if (resolvedData[index].y === 0) {
          let a = 1;
          arr.push(a);
        }
      });
      if (resolvedData.length === arr.length) {
        let fell = { x: '暂无数据', y: 1 };
        resolvedData.push(fell);
        this.setState({ colorsa: ['#00c2f3', '#f7b136', '#ccc'] });
      }
      solvePieDataA = resolvedData;
    } else {
      let arr = [];
      resolvedInUserData.map((item, index) => {
        if (resolvedInUserData[index].y === 0) {
          let a = 1;
          arr.push(a);
        }
      });
      if (resolvedInUserData.length === arr.length) {
        let fell = { x: '暂无数据', y: 1 };
        resolvedInUserData.push(fell);
        this.setState({ colorsa: ['#74ae16', '#e23e0d', '#ccc'] });
      }
      solvePieDataA = resolvedInUserData;
    }

    const visDate = [
      { x: '2019-04-13', y: 7 },
      { x: '2019-04-14', y: 5 },
      { x: '2019-04-15', y: 4 },
      { x: '2019-04-16', y: 2 },
      { x: '2019-04-17', y: 4 },
      { x: '2019-04-18', y: 7 },
      { x: '2019-04-19', y: 5 },
      { x: '2019-04-20', y: 6 },
    ];
    const visDateA = [
      { x: '2011-04-21', y: 5 },
      { x: '2011-04-22', y: 9 },
      { x: '2011-04-23', y: 6 },
      { x: '2011-04-24', y: 3 },
      { x: '2011-04-25', y: 1 },
      { x: '2011-04-26', y: 5 },
      { x: '2011-04-27', y: 3 },
      { x: '2011-04-28', y: 6 },
      { x: '2011-04-29', y: 5 },
    ];

    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <Row className={styles.colorBackground}>
            <Col style={{ padding: 10, color: '#4B5475', fontWeight: 600 }} sm={24} md={12}>
              <div className={styles.title}>
                <FormattedMessage id="app.IntroduceRow.proportion-statistical" />
                <span style={{ marginLeft: 2,paddingTop:2 }}>
                  <Tooltip
                    placement="top"
                    title="该页面展示问答命中分布情况，可任意切换时间查看。"
                    arrowPointAtCenter
                  >
                    <Icon type="info-circle" />
                  </Tooltip>
                </span>
              </div>
            </Col>
            <Col style={{ padding: 10 }} sm={24} md={12}>
              <Form layout="inline" style={{ float: 'right' }}>
                <FormItem>
                  <RangePicker
                    onChange={this.onChange}
                    style={{ width: 220 }}
                    defaultValue={[
                      moment(this.state.beginTime, dateFormat),
                      moment(this.state.overTime, dateFormat),
                    ]}
                    format={dateFormat}
                  />
                </FormItem>
                <FormItem className="buttonYs">
                  <Button onClick={this.handleSubmit} icon="check">
                    {/* 查看 */}
                    <FormattedMessage id="app.answerDetail.examine" defaultMessage="Examine" />
                  </Button>
                </FormItem>
              </Form>
            </Col>
          </Row>
          <div className="cart">
            <Card bordered={false}>
              <div>
                <Suspense fallback={<PageLoading />}>
                  <IntroduceRow
                    loading={loading}
                    chatCountList={chatCountList}
                    systemCountList={systemCountList}
                    answerRatioStatis={answerRatioStatis}
                    unknownCountList={unknownCountList}
                    userCountList={userCountList}
                    curve={this.state.curve}
                  />
                </Suspense>
              </div>
            </Card>
          </div>

          <div className={styles.twoColLayout}>
            <Row gutter={24}>
              <Col xl={12} lg={24} md={24} sm={24} xs={24}>
                <Suspense fallback={null}>
                  <ProportionSales
                    colors={this.state.colors}
                    allTitle={this.state.allTitle}
                    salesType={salesType}
                    loading={loading}
                    salesPieData={salesPieData} // 数据
                    handleChangeSalesType={this.handleChangeSalesType}
                  />
                </Suspense>
              </Col>
              <Col xl={12} lg={24} md={24} sm={24} xs={24}>
                <Suspense fallback={null}>
                  <SolveeProportion
                    colors={this.state.colorsa}
                    allTitle={this.state.allTitleA}
                    salesType={solveType}
                    loading={loading}
                    salesPieData={solvePieDataA} // 数据
                    handleChangeSalesType={this.handleChangesolveType}
                  />
                </Suspense>
              </Col>
            </Row>
          </div>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

// export default; //antd图表
export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(AnswerRatio));
